package com.foreknow.controller;

import com.foreknow.bean.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器端响应给客户端的内容的类型
        resp.setContentType("text/html;charset=UTF-8");
        //客户端向服务器端发送请求的编码
        req.setCharacterEncoding("UTF-8");

        PrintWriter out = resp.getWriter();
        //获取请求的参数
        String name =  req.getParameter("name");
        String phone =  req.getParameter("phone");
        String email =  req.getParameter("email");
        String title =  req.getParameter("title");
        String content =  req.getParameter("content");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String createdTime = sdf.format(date);

        GuestbookService service = new GuestbookServiceImpl();
        //将从页面中获取到的数据封装到Guestbook对象中
        Guestbook gb = new Guestbook();
        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        gb.setCreatedTime(createdTime);
        //调用Service中的添加留言的方法
       boolean isRigth =  service.save(gb);
       if(isRigth){
            //out.println("<a href='foreknow_webdemo/user/get'>query info</a>");
           //请求转发(刷新页面重新添加一遍再转回当前页）
//           req.getRequestDispatcher("/user/get").forward(req,resp);
           req.getRequestDispatcher("/user/manager?q=list").forward(req,resp);
           //重定向
//           resp.sendRedirect("/foreknow_webdemo/user/get");

       }else {
           out.println("add fail......");
       }

    }
}
